#!/usr/bin/env python
# Create PY incident in Prod ServiceNow category EM

import logging, os, datetime, ConfigParser
from SOAPpy import SOAPProxy

# Get OMD instance
site = os.environ['NOTIFY_OMD_SITE']
omd_root = os.environ['NOTIFY_OMD_ROOT']

# Read configuration
conf = 'snow_ticketer.ini'
fc = open(conf)
config = ConfigParser.RawConfigParser()
config.readfp(fs)
username = config.get('snow', 'username')
password = config.get('snow', 'password')
instance = config.get('snow', 'instance')
page = config.get('snow', 'page')
logf = config.get('log', 'logfile')
fc.close()

# Setup logging
logfile = omd_root + '/var/log/' + logf
logging.basicConfig(filename=logfile, format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG)

# Setup access to ServiceNow
proxy = 'https://' + username + ':' + password + '@' + instance + '.service-now.com/' + page + '?SOAP'
namespace = 'http://' + instance + '.service-now.com/'

# Setup access to Nagios command file 
commandfile = omd_root + '/tmp/run/nagios.cmd'
comf = open(commandfile, 'a')

#print(os.environ)
#logging.info(os.environ)

def createincident(params_dict):
	server = SOAPProxy(proxy, namespace)
	
	try:
		response = server.insert(cmdb_ci=(params_dict['host']), impact=(params_dict['impact']), assignment_group=(params_dict['group']), short_description=(params_dict['shortdesc']), description=(params_dict['desc']), category=(params_dict['category']), subcategory=(params_dict['subcategory']))
		return(response)
	except:
		print('Error, error')
		logging.error('Error, error')
		exit (1)

def main():
	what = os.environ['NOTIFY_WHAT']
	host = os.environ['NOTIFY_HOSTNAME']
	hoststate = os.environ['NOTIFY_HOSTSTATE']
	hostoutput = os.environ['NOTIFY_HOSTOUTPUT']

	service = os.environ['NOTIFY_SERVICEDESC']
	serviceoutput = os.environ['NOTIFY_SERVICEOUTPUT']
	servicestate = os.environ['NOTIFY_SERVICESTATE']

	group = os.environ['NOTIFY_CONTACTALIAS']
	longdatetime = os.environ['NOTIFY_LONGDATETIME']

	category = 'EM'
	subcategory = 'Nagios'

	print(hoststate, servicestate, group, longdatetime)
	logging.info(hoststate, servicestate, group, longdatetime)

	if what == 'HOST':
		problem = os.environ['NOTIFY_HOSTPROBLEMID']
		lastproblem = os.environ['NOTIFY_LASTHOSTPROBLEMID']

		shortdesc = host + " is " + hoststate
		desc = "Host: " + host + "\nState: " + hoststate + "\nTime: " + longdatetime + "\nDescription: " + hostoutput + "\n" 

		if hoststate == 'DOWN':
			impact = 1
			options = {'host': host, 'state': hoststate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': problem, 'category': category, 'subcategory': subcategory}
		elif hoststate == 'UNREACHABLE':
			impact = 2
			options = {'host': host, 'state': hoststate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': problem, 'category': category, 'subcategory': subcategory}
		elif hoststate == 'UP':
			impact = 0
			options = {'host': host, 'state': hoststate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': lastproblem, 'category': category, 'subcategory': subcategory}
		else:
                        print('Invalid host state')
                        logging.error('Invalid host state')

		print(options)
		logging.debug(options)
	
		new_incident = createincident(options)
		print(new_incident)
		logging.debug(new_incident)

		incident = new_incident['number']
		logging.info(longdatetime + ' Created incident: ' + incident)

		now = datetime.datetime.strftime(datetime.datetime.now(), '%s')	
		comf.write('[' + now + '] ACKNOWLEDGE_HOST_PROBLEM;' + host + ';2;0;0;OMD Admin;SNow Incident ' + incident + ' created\n')


	elif what == 'SERVICE':
		problem = os.environ['NOTIFY_SERVICEPROBLEMID']
		lastproblem = os.environ['NOTIFY_LASTSERVICEPROBLEMID']

		shortdesc = service + ' on ' + host + ' is ' + servicestate
		desc = 'Host: ' + host + '\nService: ' + service + '\nState: ' + servicestate + '\nTime: ' + longdatetime + '\nDescription: ' + serviceoutput + '\n' 

		if servicestate == 'CRITICAL':
			impact = 3
			options = {'host': host, 'state': servicestate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': problem,  'category': category, 'subcategory': subcategory}
		elif servicestate == 'WARNING':
			impact = 4
			options = {'host': host, 'state': servicestate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': problem,  'category': category, 'subcategory': subcategory}
		elif servicestate == 'UNKNOWN':
			impact = 5
			options = {'host': host, 'state': servicestate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': problem,  'category': category, 'subcategory': subcategory}
		elif servicestate == 'OK':
			impact = 0
			options = {'host': host, 'state': servicestate, 'impact': impact, 'group': group, 'shortdesc': shortdesc, 'desc': desc, 'problem': lastproblem,  'category': category, 'subcategory': subcategory}
		else:
			print('Invalid service state')
			logging.error('Invalid service state')

		print(options)
		logging.debug(options)

		new_incident = createincident(options)
		print(new_incident)
		logging.debug(new_incident)

		incident = new_incident['number']
		logging.info(longdatetime + ' Created incident: ' + incident)

		now = datetime.datetime.strftime(datetime.datetime.now(), '%s')	
		comf.write('[' + now + '] ACKNOWLEDGE_SVC_PROBLEM;' + host + ';' + service + ';2;0;0;OMD Admin;SNow Incident ' + incident + ' created\n')

	else:
		print('Unknown alert')
		logging.error('Unknown alert')



if __name__ == '__main__':
	main()
